#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from oriolus.docker.scripts.runner import RunnerError
from oriolus.pith.packets.packet import Status

import common
import logging


class RemoveError(common.CommandError):
    def __init__(self, message):
        common.CommandError.__init__(self, message)
        self.__message = message

    def __str__(self):
        return self.__message

class RemoveCommand(common.Command):
    def __init__(self, scripts_runner):
        self.__logger = logging.getLogger("RemoveCommand")
        self.__remove_script_names = ("preremove", "remove", "postremove")
        self.__runner = scripts_runner

    def execute(self, packet, args):
        self.__logger.info("Packet with name = %s will be removed", packet.name)

        remove_scripts = []
        for script_name in self.__remove_script_names:
            remove_scripts += [script for script in packet.scripts if script.name == script_name]

        self.__logger.debug("Execute remove scripts")
        self.__runner.prepare()
        try:
            func = lambda x: self.__runner.run(x, args)
            map(func, remove_scripts)
        except RunnerError, ex:
            packet.status = Status.BAD
            message = "Error during remove packet %s has occurred: %s" % (packet.name, ex)
            if self.__logger.isEnabledFor(logging.DEBUG):
                self.__logger.exception(message)
            else:
                self.__logger.error(message)
            raise RemoveError(message)
        else:
            packet.status = Status.REMOVED
